<?php
/**
 * Lazyest_Folder_Editor
 * All functions to manage the Folder Edit screen
 * 
 * @package Lazyest Gallery
 * @subpackage Admin/Folder Editor
 * @author Marcel Brinkkemper
 * @copyright 2012
 * @version 2.0.0 (r443)
 * @since 2.0.0 (r362)
 * @access public
 */
 
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;  
 
class Lazyest_Folder_Editor {
	
	/**
	 * @staticvar Lazyest_Folder_Editor $instance single object in memory
	 * @access private
	 */ 
	private static $instance;
	
	/**
	 * Lazyest_Folder_Editor::__construct()
	 * 
	 * @return void
	 */
	function __construct() {}
	
	/**
	 * Lazyest_Folder_Editor::init()
	 * 
	 * @since 2.0.0 (r405)
	 * @return void
	 */
	private function init() {
		$this->actions();
		$this->filters();
	}
	
	/**
	 * Lazyest_Folder_Editor::instance()
	 * Return single object in memory
	 * 
	 * @since 2.0.0 (r405)
	 * @return Lazyest_Folder_Editor object
	 */
	public static function instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new Lazyest_Folder_Editor;
			self::$instance->init();
		}
		return self::$instance;
	}
	
	/**
	 * Lazyest_Folder_Editor::actions()
	 * Add WordPress actions
	 * Apply filter 'lazyest_gallery_before_list_items_action' on action before the images list is built
	 * can be either 
	 *  'collect_images' : collect new (ftp)  uploaded images when user opens the folder edit screen ( default ) 
	 *  'no_action'      : take no action
	 * 
	 * @since 2.0.0 (r362)
	 * @uses aplly_filters()
	 * @uses add_action()
	 * @return void
	 */
	function actions() {		
		$type = lazyest_gallery()->post_type;
		$before_list_items_action = apply_filters( 'lazyest_gallery_before_list_items_action', 'collect_images' ); 
		
		$manage_action = "manage_{$type}_posts_custom_column";
  	add_action( 'admin_init',            array( $this, 'collect_folders_action' ) );
  	add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts'  ) );
  	add_action( 'admin_head',            array( $this, 'admin_style'            ) );
  	
  	add_action( 'admin_action_save_gallery',      array( $this, 'save_gallery'    ) );
  	add_action( 'admin_action_move_folder',       array( $this, 'move_folder'     ) );
  	add_action( 'admin_action_delete',            array( $this, 'delete_action'   ) );
  	add_action( 'admin_action_editpost',          array( $this, 'do_bulk_actions' ) );
  	add_action( 'admin_action_folder_action',     array( $this, 'do_bulk_actions' ) );
  	add_action( 'admin_action_attachment_action', array( $this, 'do_bulk_actions' ) );
  	add_action( 'admin_action_untrash_folders',   array( $this, 'untrash_folders' ) );
  	
  	add_action( 'admin_notices', array( $this, 'admin_notices' ) );
  	
  	add_action( 'edit_form_after_title',             array( $this, 'media_buttons'           )        );
  	add_action( 'edit_form_after_editor',            array( $this, 'list_table_attachments'  ),  1, 1 );
  	add_action( 'edit_form_after_editor',            array( $this, 'list_table_folders'      ),  2, 1 );
  	add_action( 'post_submitbox_misc_actions',       array( $this, 'folder_information'      ), 10    );
  	add_action( 'post_submitbox_misc_actions',       array( $this, 'donate'                  ), 11    );
  	add_action( $manage_action,                      array( $this, 'custom_column'           ), 10, 2 );
  	
  	add_action( 'lazyest_gallery_before_list_items', array( $this, $before_list_items_action ), 10, 1 );
  	add_action( 'lazyest_gallery_collect_folders',   array( $this, 'collect_folders'         )        );
  	
	}
	
	/**
	 * Lazyest_Folder_Editor::no_action()
	 * Do nothing
	 * @since 2.0.0 (r375)
	 * @return void
	 */
	function no_action(){}
	
	/**
	 * Lazyest_Folder_Editor::filters()
	 * Add WordPress filters
	 * 
	 * @since 2.0.0 (r362)
	 * @uses add_filter()
	 * @return void
	 */
	function filters() {
		$manage_columns = 'manage_edit-' . lazyest_gallery()->post_type . '_columns';
		
		add_filter( $manage_columns,                       array( $this, 'folder_columns'       )        );
		add_filter( 'page_row_actions',                    array( $this, 'page_row_actions'     ), 10, 2 );
		add_filter( 'upload_dir',                          array( $this, 'upload_dir'           )        );
		add_filter( 'views_edit-galleryfolder',            array( $this, 'save_columns_button'  )        );
		add_filter( 'page_attributes_dropdown_pages_args', array( $this, 'dropdown_pages_args'  ), 10, 2 );
		
		add_filter( 'media_view_strings',                  array( $this, 'media_view_strings'   ), 10, 2 );
		add_filter( 'media_send_to_editor',                array( $this, 'media_send_to_editor' ), 10, 3 );
	}
	
	/**
	 * Lazyest_Folder_Editor::admin_enqueue_scripts()
	 * Register scripts for later use
	 * 
	 * @since 2.0.0 (r380)
	 * @uses wp_register_script()
	 * @return void
	 */
	function admin_enqueue_scripts() {
		$j = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? 'js' : 'min.js';
		wp_register_script( 'jquery-tablednd',       lazyest_gallery()->plugin_url . "admin/js/jquery.tablednd.$j",       array( 'jquery' ),          '0.7',        true );
		wp_register_script( 'lazyest-gallery-admin', lazyest_gallery()->plugin_url . "admin/js/lazyest-gallery-admin.$j", array( 'jquery-tablednd' ), '2.0.0-r399', true );
	}	
	
	/**
	 * Lazyest_Folder_Editor::bail()
	 * Do we have the right screen and action, or should we stop executing?
	 * 
	 * @since 2.0.0 (r362)
	 * @uses get_current_screen()
	 * @return bool
	 */
	private function bail() {
		if ( isset( $_GET['post_type'] ) && ( $_GET['post_type'] == lazyest_gallery()->post_type ) )
			return false;
			
		if ( ( ! isset( get_current_screen()->post_type ) ) || ( lazyest_gallery()->post_type != get_current_screen()->post_type ) )
			return true;			
			
		return false;
	}
	
	/**
	 * Lazyest_Folder_Editor::admin_notices()
	 * Show notices after custom actions
	 * 
	 * @since 2.0.0 (r393)
	 * @uses get_current_screen()
	 * @uses remove_query_arg()
	 * @uses  add_query_arg()
	 * @uses wp_nonce_url()
	 * @uses number_format_i18n()
	 * @uses absint()
	 * @return void
	 */
	function admin_notices() {
		// only process notices for the lazyest gallery
		if ( $this->bail() )
			return;
		$screen = get_current_screen();			
		$message = '';	
		
		if ( 'post' ==  $screen->base && lazyest_gallery()->post_type == $screen->id ) {
			if ( isset( $_GET['post'] ) && ! empty( $_GET['deleted'] ) && $deleted = absint( $_GET['deleted'] ) ) {
				$message = sprintf( _n( 'Image attachment permanently deleted.', '%d image attachments permanently deleted.', $deleted, 'lazyest-gallery' ), number_format_i18n( $_GET['deleted'] ) );
				$_SERVER['REQUEST_URI'] = remove_query_arg(array('deleted'), $_SERVER['REQUEST_URI']);
			}
			if ( isset( $_REQUEST['trashed'] ) && $trashed = absint( $_REQUEST['trashed'] ) ) {
				$post_type = lazyest_gallery()->post_type;
				$message = sprintf( _n( 'Folder moved to the Trash.', '%s folders moved to the Trash.', $trashed, 'lazyest-gallery' ), number_format_i18n( $trashed ) );
				$ids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : 0;				
				$_SERVER['REQUEST_URI'] = remove_query_arg( array( 'trashed' ), $_SERVER['REQUEST_URI'] );
				$undo_url = wp_nonce_url( add_query_arg( array( 'ids' => $ids, 'action' => 'untrash_folders' ), $_SERVER['REQUEST_URI'] ), 'bulk-posts' );
				$message .= ' <a href="' . $undo_url . '">' . __( 'Undo' ) . '</a>';
			}
			
			if ( isset( $_REQUEST['untrashed'] ) && $untrashed = absint( $_REQUEST['untrashed'] ) ) {
				$message = sprintf( _n( 'Folder restored from the Trash.', '%s folders restored from the Trash.', $untrashed, 'lazyest-gallery' ), number_format_i18n( $untrashed ) );					
				$_SERVER['REQUEST_URI'] = remove_query_arg( array( 'untrashed' ), $_SERVER['REQUEST_URI'] );
			}	
			if ( empty( $message ) )
				return;
			?>
			<div class="updated"><p><?php echo $message ?></p></div>
			<?php
			return;			
		}					
		if ( isset( $_REQUEST['parent-of'] ) ) {
			$message = __( 'You cannot delete a parent folder', 'lazyest-gallery' );
			$_SERVER['REQUEST_URI'] = remove_query_arg( array( 'parent-of' ), $_SERVER['REQUEST_URI'] );
		}
			
		if ( empty( $message ) )
			return;
		?>
		<div class="error"><p><?php echo $message ?></p></div>
		<?php
	}
	
	/**
	 * Lazyest_Folder_Editor::delete_action()
	 * Prevent users to permanently delete parent folders
	 * Return to edit page with message
	 * 
	 * @since 2.0.0 (r400)
	 * @uses get_post()
	 * @uses get_children()
	 * @uses wp_redirect()
	 * @uses add_query_arg()
	 * @uses wp_get_referer()
	 * @return void
	 */
	function delete_action() {
		global $post_type, $post_ids;
		$post_ids = !empty( $_REQUEST['post'] ) ? array_map( 'intval', (array) $_REQUEST['post'] ) : null;
		$post_type = isset( $_REQUEST['post_type'] ) ? $_REQUEST['post_type'] : null; 
		if ( ! isset( $post_type ) || $post_type != lazyest_gallery()->post_type )
			return;
		if ( isset( $post_ids ) ) {
			foreach( (array) $post_ids as $post_id ) {
				$has_subfolders = lazyest_folderbase()->get_subfolders( $post_id );
				if ( ! empty( $has_subfolders ) ) {
					wp_redirect( add_query_arg( array( 'parent-of' => count( $has_subfolders ) ), wp_get_referer() ) );
					exit; 	
				}	
			}
		}
	}
	
	/**
	 * Lazyest_Folder_Editor::do_bulk_actions()
	 * Perform bulk actions
	 * 
	 * @since 2.0.0 (r393) 
	 * @return void
	 */
	function do_bulk_actions() {		
		$buttons = array( 'attachment_action', 'attachment_action2', 'folder_action', 'folder_action2' );
		$return = true;
		foreach( $buttons as $button )
			if ( isset( $_REQUEST[$button] ) && -1 != $_REQUEST[$button] ) {
				$action = false === strpos( $button, 'attachment' ) ? 'bulk_trash_folders' : 'bulk_delete_attachments';					
				$return = false;
			}				
		if ( $return ) return;
		
		$this->$action();
	}
	
	/**
	 * Lazyest_Folder_Editor::bulk_trash_folders()
	 * Trash one or more subfolders
	 * 
	 * @since 2.0.0 (r393)
	 * @uses check_admin_referer()
	 * @uses wp_get_referer()
	 * @uses remove_query_arg()
	 * @uses get_post_type_object()
	 * @uses current_user_can()
	 * @uses wp_die()
	 * @uses wp_trash_post()
	 * @uses add_query_arg()
	 * @uses wp_redirect() 
	 * @return void
	 */
	function bulk_trash_folders() {
		check_admin_referer( 'bulk-folders', 'bulk-folders' );
		
		$sendback = wp_get_referer();
		$sendback = remove_query_arg( array('trashed', 'untrashed', 'deleted', 'ids', 'message' ), $sendback );
		if ( isset( $_REQUEST['folders'] ) && 0 < count( $_REQUEST['folders'] ) ) {
			$trashed = 0;
			$post_type_object = get_post_type_object( lazyest_gallery()->post_type );
			foreach( (array) $_REQUEST['folders'] as $folder ) {					
				if ( ! current_user_can( $post_type_object->cap->delete_post, intval( $folder ) ) )						
					wp_die( __( 'You are not allowed to move this folder to the Trash.', 'lazyest-gallery' ) );
					
				if ( false !== wp_trash_post( intval( $folder ) ) )
					$trashed++;	
			}
			$sendback = add_query_arg( array( 'trashed' => $trashed, 'ids' => join( ',', ( array ) $_REQUEST['folders'] ) ), $sendback );					
		}
		wp_redirect( $sendback );
		exit();					
	}
	
	/**
	 * Lazyest_Folder_Editor::untrash_folders()
	 * Undo trashing of one or more folders
	 * 
	 * @since 2.0.0 (r393)
	 * @uses admin_url()
	 * @uses check_admin_referer()
	 * @uses get_post_type_object()
	 * @uses current_user_can()
	 * @uses get_post()
	 * @uses wp_untrash_post()
	 * @uses wp_die()
	 * @uses add_query_arg()
	 * @uses wp_redirect()
	 * @return void
	 */
	function untrash_folders() {
		check_admin_referer('bulk-posts');
					
		$sendback = add_query_arg( array( 'action' => 'edit' ), admin_url( 'post.php' ) );
				
		$post_ids = array();
		$post_type_object = get_post_type_object( lazyest_gallery()->post_type );
		if ( isset( $_REQUEST['ids'] ) ) {
			$post_ids = explode( ',', $_REQUEST['ids'] );
			$untrashed = 0;
			foreach( (array) $post_ids as $post_id ) {
				if ( ! current_user_can( $post_type_object->cap->delete_post, intval( $post_id ) ) )
					wp_die( __( 'You are not allowed to restore this folder from the Trash.', 'lazyest-gallery' ) );
				
				$parent_id = get_post( $post_id )->post_parent;
				if ( ! wp_untrash_post( $post_id ) )
					wp_die( __('Error in restoring from Trash.', 'lazyest-gallery' ) );

				$untrashed++;
			}
			$sendback = add_query_arg( array( 'untrashed' => $untrashed, 'post' => $parent_id ), $sendback );
			wp_redirect( $sendback );
			exit();			
		}	
	}
	
	/**
	 * Lazyest_Folder_Editor::bulk_delete_attachments()
	 * Permanently delete one or more image attachments
	 * 
	 * @since 2.0.0 (r393)
	 * @uses check_admin_referer()
	 * @uses wp_get_referer()
	 * @uses get_post_type_object()
	 * @uses current_user_can()
	 * @uses wp_delete_attachment()
	 * @uses wp_die()
	 * @uses add_query_arg()
	 * @uses wp_redirect()
	 * @return void
	 */
	function bulk_delete_attachments() {
		check_admin_referer( 'bulk-media', 'bulk-media' );
		
		$sendback = wp_get_referer();
		$sendback = remove_query_arg( array('trashed', 'untrashed', 'deleted', 'ids', 'message' ), $sendback );
		
		if ( isset( $_REQUEST['media'] ) && 0 < count( $_REQUEST['media'] ) ) {
			$deleted = 0;
			$post_type_object = get_post_type_object( 'attachment' );
			foreach( (array) $_REQUEST['media'] as $media ) {									
				if ( !current_user_can( $post_type_object->cap->delete_post, intval( $media ) ) )						
					wp_die( __( 'You are not allowed to delete this image.', 'lazyest-gallery' ) );
					
				if ( false !== wp_delete_attachment( intval( $media ), true ) )
					$deleted++;	
			}
			$sendback = add_query_arg( array( 'deleted' => $deleted ), $sendback );					
		}
		wp_redirect( $sendback );
		exit();
	}

	/**
	 * Lazyest_Folder_Editor::save_gallery()
	 * Save Gallery menu order triggered by Save Changes button on manually sorted Folders list
	 * Redirect back and show number of updated posts
	 * 
	 * @since 2.0.0 (r380)
	 * @uses check_admin_referer()
	 * @uses wp_redirect()
	 * @uses admin_url()
	 * @return void
	 */
	function save_gallery() {
		$updated = 0;
		if ( ! empty( $_POST ) && check_admin_referer( 'save_gallery-pages','gallery_nonce-pages') ) {
			if ( isset( $_POST['gallery-order-pages'] ) ) {
				$gallery_order = explode( ' ', $_POST['gallery-order-pages'] );
				$updated = lazyest_folderbase()->save_gallery_order( $gallery_order );
			}
		}
		wp_redirect( admin_url( "edit.php?post_type=galleryfolder&updated=$updated" ) );		
		exit;		
	}
	
	/**
	 * Lazyest_Folder_Editor::move_folder()
	 * Move folder to top or to bottom of the list
	 * 
	 * @since 2.0.0 (r380)
	 * @uses wp_redirect()
	 * @uses admin_url()
	 * @return void
	 */
	function move_folder() {
		$updated = 0;
		if ( ! empty( $_GET ) && check_admin_referer( 'move_folder' ) ) {
			if ( isset( $_GET['move'] ) && isset( $_GET['folder'] ) ) {
   			$updated = lazyest_folderbase()->move_folder( $_GET['folder'], $_GET['move'] );
			}
  	}
		wp_redirect( admin_url( "edit.php?post_type=galleryfolder&updated=$updated" ) );
		exit;
	}
	
	/**
	 * Lazyest_Folder_Editor::collect_folders()
	 * Call Lazyest_FolderBase::collect_folders to get all (ftp) uploaded folders
	 * 
	 * @since 2.0.0 (r362)
	 * @return void
	 */
	function collect_folders() {
		if ( $this->bail() )
			return;						
		$post_id = isset( get_current_screen()->post_ID ) ? get_current_screen()->post_ID : 0; 	
		lazyest_folderbase()->collect_folders( $post_id );
	}
	
	function collect_folders_action() {
		do_action( 'lazyest_gallery_collect_folders' );
	}
	
	/**
	 * Lazyest_Folder_Editor::collect_images()
	 * Call Lazyest_FolderBase::collect_images to get all (ftp) uploaded images
	 * 
	 * @since 2.0.0 (r375)
	 * @param mixed $folder_id
	 * @return void
	 */
	function collect_images( $folder_id ) {
		lazyest_folderbase()->collect_images( $folder_id );
	}
	
	/**
	 * Lazyest_Folder_Editor::admin_style()
	 * Add style rules for the Folder Edit screen to the Admin <head> element
	 * 
	 * @since 2.0.0 (r362)
	 * @return void
	 */
	function admin_style() {
		if ( $this->bail() )
			return;			
		$folder_icon_url = isset( $_GET['post_type'] ) ? 
			lazyest_gallery()->plugin_url . 'admin/images/file-manager-icon.png' : 
				lazyest_gallery()->plugin_url . 'admin/images/folder-icon.png';
		// styling for post_type galleryfolder pages							
		?>
		<style type="text/css">
			.fixed .column-galleryfolder_images {
				width: 8em;
			}
			.fixed .column-galleryfolder_new {
				vertical-align: middle;
				width: 16px;
			}
			.fixed .column-galleryfolder_drag, .fixed .column-media_drag {
				display: none;
				padding:0;
				text-align: center;
				vertical-align: middle;
				width:32px;
			}
			.fixed td.column-galleryfolder_drag, .fixed td.column-media_drag {				
				background-color: #f3f3f3;
				border-right:  1px dotted #aaa;
				border-left:  1px dotted #aaa;				
				cursor: -moz-grab;
				cursor: -webkit-grab;
				cursor: grab;
			}
			.fixed tr.dragging td.column-galleryfolder_drag, .fixed tr.dragging td.column-media_drag {
				cursor: -moz-grabbing;
				cursor: -webkit-grabbing;
				cursor: grabbing;				
			}
			.fixed tr.dragging {
				background-color:  #fff;
				text-shadow: 4px 4px #C6C6C6;
			}
			input[type="text"].attachment-title {
				width:90%;
			}
			div.after-editor {
				margin-top: 20px;
			}
			div.attachment-content {
				margin-top: 8px;
				margin-bottom: 10px;
				width: 90%;
			}
			.tablenav .tablenav-pages a.add-subfolder {
				font-family: sans-serif;
				font-weight:  normal;
				margin-left: 4px;
				padding: 3px 8px;
				position: relative;
				top: -3px;
				text-decoration: none;
				font-size: 12px;
				border: 0 none;
			}
			#icon-edit.icon32.icon32-posts-galleryfolder {
				background:  transparent url('<?php echo $folder_icon_url ?>') no-repeat;
			}
			.edit-tags-php #icon-edit.icon32.icon32-posts-galleryfolder {
				background: transparent url('<?php echo $folder_icon_url ?>') no-repeat;
			}
			.subsubsub a.save-gallery:hover {
				color:#fff;
			}
			.button.button-large.media-button-gallery {
				height: 0;
				padding: 0;
			}
			.media-menu-item:empty {
				display: none;
			}
		</style>
		<?php	
	}
	
	/**
	 * Lazyest_Folder_Editor::folder_columns()
	 * Add custom columns to the posts list
	 * 
	 * @since 2.0.0 (r362)
	 * @param array $columns
	 * @return array
	 */
	function folder_columns( $columns ) {
		$type = lazyest_gallery()->post_type;		
		$drag_url = lazyest_gallery()->plugin_url . 'admin/images/sort.png';
		$post_status = isset( $_REQUEST['post_status'] ) ? $_REQUEST['post_status'] : ''; 
		$columns = array();
		$columns['cb'] = '<input type="checkbox" />';
		if (  'menu_order-ASC' == lazyest_gallery()->sort_by() && $post_status != 'trash' ) 
			$columns["{$type}_drag"] = '<img src="' . $drag_url . '" alt="' . __( 'Draggable Column', 'lazyest-gallery' ) .  '" style="width:16px; height=16px"/>';
		$columns["{$type}_path"]   = _x( 'Name',    'column name', 'lazyest-gallery' );
		$columns['title']          = _x( 'Caption', 'column name', 'lazyest-gallery' );
		$columns["{$type}_images"] = _x( 'Images',  'column name', 'lazyest-gallery' );
		$columns['tags']           = _x( 'Tags',    'column name'                    );
		$columns['comments']       = '<span><span class="vers"><div title="' . esc_attr__( 'Comments' ) . '" class="comment-grey-bubble"></div></span></span>';
		$columns["{$type}_new"]    = '';
		$columns['date']           = _x( 'Date' ,   'column name' );
		return $columns;
	}
	
	/**
	 * Lazyest_Folder_Editor::page_row_actions()
	 * Add 'to Top' and 'to Bottom' links to row actions below caption
	 * 
	 * @since 2.0.0 (r380)
	 * @param array $actions
	 * @param stdClass $post
	 * @uses admin_url()
	 * @uses add_query_arg()
	 * @uses get_children()
	 * @uses get_current_screen()
	 * @return array 
	 */
	function page_row_actions( $actions, $post ) {
		$post_type = lazyest_gallery()->post_type;
		$move_url = wp_nonce_url( add_query_arg( array( 
				'post_type' => $post_type, 
				'folder'    => $post->ID, 
				'action'    =>	'move_folder'
			), admin_url( 'edit.php' ) ), 'move_folder' );
		$to_top_url    = add_query_arg( array( 'move' => 'to_top'    ), $move_url );
		$to_bottom_url = add_query_arg( array( 'move' => 'to_bottom' ), $move_url ); 
		if ( $post->post_type == $post_type && $post->post_status != 'trash' ) {
			$actions["to-top to-top-{$post->ID}"]       = "<a href='$to_top_url'>"    . __( 'to Top&nbsp;&#8593;', 'lazyest-gallery'   ) . "</a>";
			$actions["to-bottom to-bottom-{$post->ID}"] = "<a href='$to_bottom_url'>" . __( 'to Bottom&nbsp;&#8595;', 'lazyest-gallery') . "</a>";
		}			
		if ( 'trash' == $post->post_status ) {
			if ( lazyest_folderbase()->has_subfolders( $post->ID ) )
				unset( $actions['delete'] ); 
		}
		$screen = get_current_screen();
		if ( 'post' ==  $screen->base && $post_type == $screen->id ) {
			$actions['trash'] = '<a class="submitdelete" title="' . __( 'Move this folder to the Trash', 'lazyest-gallery' ) . '" href="' . add_query_arg( array( 'post' => $post->post_parent, 'action' => 'folder_action', 'folder_action' => 'trash', 'folders' => $post->ID, 'bulk-folders' => wp_create_nonce( 'bulk-folders') ), admin_url( 'post.php') ) . '">' . __( 'Trash', 'lazyest-gallery' ) . '</a>';	
		}		
		return $actions;
	}
	
	/**
	 * Lazyest_Folder_Editor::custom_column()
	 * Output custom colmn for the post list
	 * 
	 * @since 2.0.0 (r362)
	 * @param string $column
	 * @param int $post_id
	 * @return void
	 */
	function custom_column( $column, $post_id ) {
		$type = lazyest_gallery()->post_type;
		switch( $column ) {
			case "{$type}_drag" :
				echo $this->drag_handle( $post_id ); 
				break;
			case "{$type}_images" :
				echo $this->get_image_count( $post_id );
				break;
			case "{$type}_path" :
				echo $this->get_folder_path_display( $post_id );
				break;
			case "{$type}_new" :
				echo $this->get_new_folder_display( $post_id );	
		}
	}
	
	/**
	 * Lazyest_Folder_Editor::get_new_folder_display()
	 * Display a little star in column prior to Date to show recently added Folder
	 * Use filter 'lazyest_gallery_folder_star_days' to change number of days to show the star (default 1)
	 * 
	 * @since 2.0.0 (r380)
	 * @uses apply_filters()
	 * @uses get_post_time()
	 * @param mixed $post_id
	 * @return string <img> element
	 */
	function get_new_folder_display( $post_id ) {
		$days = apply_filters( 'lazyest_gallery_folder_star_days', 1 );
		$star_src = lazyest_gallery()->plugin_url . 'admin/images/new-item.png';
		$star_alt = __( 'Posted less than one day ago', 'lazyest-gallery' ); 
		$new_item = "<img src='$star_src' alt='$star_alt' title='$star_alt' style='width:16px; height=16px' />";
		$post_time = get_post_time( 'U', true, $post_id ); 	
		return ( $days * 86401 > ( time() - $post_time ) ) ? $new_item : '';		 
	}
	
	/**
	 * Lazyest_Folder_Editor::get_image_count()
	 * Count attachments for this Folder
	 * 
	 * @since 2.0.0 (r362)
	 * @uses get_children()
	 * @param int $post_id
	 * @return int
	 */
	function get_image_count( $post_id ) {
		$attachments = get_children( array(
			'post_parent' => $post_id,
	    'post_type'   => 'attachment', 
	    'numberposts' => -1,
	    'post_status' => 'any'
		) );
		return count( $attachments );	
	}	
	
	/**
	 * Lazyest_Folder_Editor::drag_handle()
	 * html for inside drag-handle <td>
	 * 
	 * @since 2.0.0 (r380)
	 * @param integer $post_id
	 * @return string
	 */
	function drag_handle( $post_id ) {
		$drag_handle  = "<span class='hide-if-no-js' title='" . __( 'Click an hold to sort', 'lazyest-gallery' ) . "'>&#8230;</span>";
		$drag_handle .= "<input class='drag-id' type='hidden' name='post_id-{$post_id}' value='{$post_id}' />";
		return $drag_handle; 
	}
	
	/**
	 * Lazyest_Folder_Editor::display_subdirectories()
	 * Display a list of sub-directories in admin list table
	 * 
	 * @since 2.0.0 (r402)
	 * @uses current_user_can()
	 * @uses get_edit_post_link()
	 * @uses esc_attr()
	 * @param integer $post_id
	 * @return html markup of unordered list of subdirectories
	 */
	function display_subdirectories( $post_id ) {
		$subdirectories = lazyest_folderbase()->get_subdirectories( $post_id );
		$display = '';
		if ( ! empty( $subdirectories ) ){
			$display .= "\n<ul class='sub-directories'>";
			foreach( $subdirectories as $directory ) {
				$display .= "\n\t<li>";
				$edit_name = basename( $directory );				
				$edit_name  = str_repeat( '&#8212; ', substr_count( $directory, '/' ) ) . $edit_name;
				$sub_id = lazyest_folderbase()->get_folder_by_path( $directory );
				if ( current_user_can( 'edit_post', $sub_id ) ) {					
					$edit_link  = get_edit_post_link( $sub_id, true );
					$edit_title = esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $directory ) );
					$display   .= "<a href='$edit_link' title='$edit_title'>$edit_name</a> ";
				} else {
					$display .= "$edit_name"; 
				}
				$display .= "</li>";
			}
			$display .= "\n</ul>";
		}
		return $display;
	}	
	
	/**
	 * Lazyest_Folder_Editor::get_folder_path_display()
	 * Get display text for folder path
	 * 
	 * @since 2.0.0 (r362)
	 * @uses get_post_meta()
	 * @param int $post_id
	 * @return string 
	 */
	function get_folder_path_display( $post_id, $for = 'table' ) {
		global $post;
  	$gallery_path = get_post_meta( $post_id, 'gallery_path', true );
		$display = __( 'Not Saved', 'lazyest-gallery' );
		
		if ( ! empty( $gallery_path ) ) {
			$edit_name = basename( $gallery_path ); 
			if ( 'table' == $for )
				$edit_name  = str_repeat( '&#8212; ', substr_count( $gallery_path, '/' ) ) . $edit_name;
			if ( ( $post->ID == $post_id && 'table' != $for ) || ! current_user_can( 'edit_post', $post_id ) ) {
				$display    = " <strong>$edit_name</strong> ";
			} else {
				$edit_link  = get_edit_post_link( $post_id, true );
				$edit_title = esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $gallery_path ) );
				$display    = " <strong><a href='$edit_link' title='$edit_title'>$edit_name</a></strong> ";
			}
			
			// show sub-directories in manually sorted lists
			if ( 'table' == $for && lazyest_gallery()->sort_by() == 'menu_order-ASC' )
				$display .= $this->display_subdirectories( $post_id );				
		}			
		return $display;		
	}
	
	/**
	 * Lazyest_Folder_Editor::hidden_order_field()
	 * Add a hidden input field with post IDs in sorted order
	 * 
	 * @param mixed $items
	 * @param string $type
	 * @return
	 */
	function hidden_order_field( $items, $type = 'pages' ) {	
		$changed = $type == 'pages' ? isset( $_GET['folder_orderby'] ) : isset( $_GET['orderby'] );
		$changed = intval( $changed );
		$hidden_order_field = wp_nonce_field( "save_gallery-{$type}", "gallery_nonce-{$type}", false, false );
		$hidden_order_field .= "\n<input type='hidden' id='gallery-order-{$type}' name='gallery-order-{$type}' value ='";
			if ( ! empty( $items ) ) {
				foreach( $items as $item ) {
					$hidden_order_field .= "{$item->ID} ";
				}
			}
			$hidden_order_field = rtrim( $hidden_order_field );
			$hidden_order_field .=  "' />";
			$hidden_order_field .= "\n<input type='hidden' id='gallery-changed-{$type}' name='gallery-changed-{$type}' value='$changed'/>\n";
		return $hidden_order_field;		
	}
	
	/**
	 * Lazyest_Folder_Editor::save_columns_button()
	 * Add a <form> and submit <input> to the Gallery list screen
	 * 
	 * @uses wp_enqueue_script()
	 * @since 2.0.0 (r380)
	 * @param array $views
	 * @return array
	 */
	function save_columns_button( $views ) {
		
		if ( ( isset( $_REQUEST['post_status'] ) && 'trash' == $_REQUEST['post_status']  ) || ( lazyest_gallery()->sort_by() != 'menu_order-ASC' ) )
			return $views;
			
		global $wp_query;
    $folders = $wp_query->posts;
    $save_button = "<form id='posts-saver' action='edit.php?action=save_gallery' method='post'>";
    $save_button .= $this->hidden_order_field( $folders );
		$post_type = lazyest_gallery()->post_type;
		$disabled = isset( $_GET['orderby'] ) ? '' : "disabled='disabled' ";
		$button_text = __( 'Save Changes', 'lazyest-gallery' );
		$save_button .= "<input type='submit' name='save_gallery' value='$button_text' id='save-order' class='button button-primary button-small save-gallery' $disabled/>";
		$save_button .= "</form>";
		$views['save-sort'] = $save_button;
		wp_enqueue_script( 'lazyest-gallery-admin' );
		
		return $views;
	}
  
  /**
   * Lazyest_Folder_Editor::media_buttons()
   * Remove Media Buttins from edit screen when Folder has not been saved yet
   * 
   * @since 2.0.0 (r362)
   * @uses get_post_meta()
   * @uses remove_all_actions()
   * @return void
   */
  function media_buttons() {
  	global $post;
  	if ( $post->post_type == lazyest_gallery()->post_type ) {
  		$gallery_path = get_post_meta( $post->ID, 'gallery_path', true );
  		if ( '' == $gallery_path ) 
				remove_all_actions( 'media_buttons' );	
  	}  		
  }
  
  /**
   * Lazyest_Folder_Editor::media_view_strings()
   * Remove and change strings in the Media uploader
   * 
   * @since 2.0.0 (r398)
   * @param array $strings
   * @param WP_post $post
   * @return array
   */
  function media_view_strings( $strings, $post ) {
		if ( lazyest_gallery()->post_type == $post->post_type ) { 		
	 		// disable some views that have no purpose in Lazyest Gallery
	 		$disabled = array( 'selectFiles', 'createNewGallery', 'fromUrlTitle', 'createGalleryTitle' );
	 		foreach( $disabled as $string )
	 			$strings[$string] = '';
	 		$strings['allMediaItems']      = __( 'Select a view', 'lazyest-gallery'           );	
	 		$strings['uploadedToThisPost'] = __( 'Uploaded to this folder', 'lazyest-gallery' );
			$strings['insertIntoPost']     = __( 'Done uploading', 'lazyest-gallery'          );	
		}
		return $strings; 						  		
  }
  
  /**
   * Lazyest_Folder_Editor::media_send_to_editor()
   * filter for 'media_send_to_editor'
   * Don't send images to editor when we are on the edit folder screen
   * 
   * @since 2.0.0 (r398)
   * @param string $html
   * @param integer $id
   * @param WP_Post $attachment
   * @return string
   */
  function media_send_to_editor( $html, $id, $attachment ) {
  	
  	if ( lazyest_folderbase()->refered_by_folder() )
  		$html = '';
  		
  	return $html;
  }
  
  /**
   * Lazyest_Folder_Editor::folder_information()
   * Output folder information in a metabox
   * 
   * @since 2.0.0 (r362)
   * @uses get_post_meta()
	 * @return void
   */
  function folder_information() {
  	if ( $this->bail() )
			return; 
  	
  	global $post;
  	$folder = $post;
  	$gallery_path = get_post_meta( $post->ID, 'gallery_path', true );
  	$path[] = $this->get_folder_path_display( $folder->ID, 'meta' ); 		  	
  	while ( 0 < $folder->post_parent ) {
  		$folder = get_post( $folder->post_parent );
  		$path[] = $this->get_folder_path_display( $folder->ID, 'metabox' ); 		  	
  	}
  	$path = array_reverse( $path );
  	$gallery_display = implode( '/', $path );
  	?>
  	<div class="misc-pub-section">	  	
	  	<p><?php echo __( 'Path: ', 'lazyest-gallery' ) . $gallery_display ?></p>
	  	<input type="hidden" id="gallery_path" name="gallery_path" value="<?php echo $gallery_path ?>" />
  	</div>
  	<?php
  }
  
  /**
   * Lazyest_Folder_Editor::donate()
   * Add a donate button to the gallleryfolder edit screen
   * 
   * @since 2.0.0 (r405)
   * @return void
   */
  function donate() {
  	if ( $this->bail() )
			return; 
  	?>
  	<div class="misc-pub-section">	  	
	  	<p>
				<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=MSWK36DKJ7GW4" title="<?php _e( 'Support the development of Lazyest Galery', 'lazyest-gallery' ); ?>">
					<img src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" alt="PayPal - The safer, easier way to pay online!" />
				</a>
			</p>
  	</div>
  	<?php
  }
  
  /**
   * Lazyest_Folder_Editor::dropdown_pages_args()
   * Change parent folder dropdown if user wants to add sub-folder
   * 
   * @since 2.0.0 (r381)
   * @uses get_current_screen()
   * @param array $dropdown_args
   * @param WP_Post $post
   * @return array
   */
  function dropdown_pages_args(  $dropdown_args, $post ) {
  	if ( $this->bail() )
  		return $dropdown_args;
  	$screen = get_current_screen();
		if ( 'add' == $screen->action && isset( $_GET['post_parent'] ) )
			$dropdown_args['selected'] = $_GET['post_parent'];
		return  $dropdown_args;		
  }
  
  /**
   * Lazyest_Folder_Editor::list_table_attachments()
   * Return list table with images to edit
   * 
   * @uses wp_enqueue_sscript()
   * @return string
   */
  function list_table_attachments() {
  	global $post;
  	if ( $this->bail() )
  		return;
 		do_action( 'lazyest_gallery_before_list_items', $post->ID );
  	require_once( lazyest_gallery()->plugin_dir . 'admin/class-lazyest-media-list-table.php' );
  	$list_table = new Lazyest_Media_List_Table( array( 'plural' => 'media'  ) );  	
		$list_table->prepare_items();
		?>
		<div id="attached-images-<?php echo $post->ID ?>" class="attached-images after-editor">
		<?php				
		if ( $list_table->has_items() ) {			
			$list_table->views();
			$list_table->display();
		}
		?>
		</div>
		<?php
		wp_enqueue_script( 'lazyest-gallery-admin' );
  }
  
  /**
   * Lazyest_Folder_Editor::list_table_folders()
   * Return list table with sub-folders to edit
   * 
   * @since 2.0.0 (r381)
   * @uses wp_enqueue_script()
   * @return string
   */
  function list_table_folders() {
  	global $post;
  	if ( $this->bail() )
  		return;
  	require_once( lazyest_gallery()->plugin_dir . 'admin/class-lazyest-folder-list-table.php' );
  	$list_table = new Lazyest_Folder_List_Table( array( 'plural' => 'pages'  ) );
		$list_table->prepare_items();
		?>
		<div id="sub-folders-<?php echo $post->ID ?>" class="sub-folders after-editor">
		<?php
		if ( $list_table->has_items() ) {
			if ( 'menu_order-ASC' == lazyest_gallery()->sort_by() )
				wp_enqueue_script( 'lazyest-gallery-admin' );			
			$list_table->views();
			$list_table->display();
		}
		?>
		</div>
		<?php
  }
  
  /**
   * Lazyest_Folder_Editor::upload_dir()
   * Filter the upload dir for Lazyest Gallery Folders
   * 
   * @param array $upload
   * @return array
   */
  function upload_dir( $upload ) {
		$post_type = isset( $_REQUEST['post_type'] ) ? $_REQUEST['post_type'] : '';
		$post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;			
		if ( 0 == $post_id ) 
			$post_id = isset( $_REQUEST['post'] ) ? intval( $_REQUEST['post'] ) : 0;
		if ( 0 != $post_id ) 				
				$post_type = get_post_type( $post_id );  								
		if ( 'attachment' == $post_type ) 
		  $post_type = get_post_type( get_post( $post_id )->post_parent );			
		// if it is galleryfolder, change upload_dir
  	if ( lazyest_gallery()->post_type == $post_type ) {
			$gallery_path = get_post_meta( $post_id, 'gallery_path', true );
			$upload['path']    = untrailingslashit( lazyest_gallery()->root()  . $gallery_path );
			$upload['url']     = untrailingslashit( lazyest_gallery()->address() . $gallery_path );
			$upload['subdir']  = untrailingslashit( $gallery_path );
			$upload['basedir'] = untrailingslashit( lazyest_gallery()->root() );
			$upload['baseurl'] = untrailingslashit( lazyest_gallery()->address() );
		} 					
		return $upload;
	}
} // Lazyest_Folder_Editor